package com.hzw.saas.common.security.config;

import com.hzw.saas.common.security.constants.SecurityConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 资源服务不注入以下类，不报错
 *
 * @author sonam
 * @sine 2021/11/2 4:08 下午
 */
@Slf4j
@Configuration
public class SecurityConfig {
    /**
     * 登录过滤器
     */
    @Bean
    @ConditionalOnMissingBean
    public AbstractAuthenticationProcessingFilter loginFilter() {
        return new AbstractAuthenticationProcessingFilter(SecurityConstants.LOGIN_URI) {
            @Override
            public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
                AuthenticationServiceException error = new AuthenticationServiceException("不支持登录操作");
                log.error("不支持登录操作", error);
                throw error;
            }

            @Autowired
            @Override
            public void setAuthenticationManager(AuthenticationManager authenticationManager) {
                super.setAuthenticationManager(authenticationManager);
            }
        };
    }

    /**
     * 用户查询业务
     */
    @Bean
    @ConditionalOnMissingBean
    public UserDetailsService userDetailsService() {
        return username -> {
            UsernameNotFoundException error = new UsernameNotFoundException("服务请实现该接口");
            log.error("服务请实现该接口", error);
            throw error;
        };
    }

    /**
     * 用户登出业务，JWT无效
     */
    @Bean
    @ConditionalOnMissingBean
    public LogoutSuccessHandler logoutSuccessHandler() {
        return (request, response, authentication) -> {
            // ignore,必要时，资源服务请注入该实现
        };
    }

}
